package com.sun.dream.fish.config.shiro;

import com.sun.dream.fish.util.ResponseUtil;
import com.sun.dream.fish.util.json.JsonUtils;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import java.io.PrintWriter;

/**
 * Description:
 * Created By ljl on 2023/12/14.
 */
@Slf4j
public class DSFFormAuthenticationFilter extends FormAuthenticationFilter {

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        return super.onLoginFailure(token, e, request, response);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        try (PrintWriter writer = httpResponse.getWriter()) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            writer.write(JsonUtils.toJsonString(ResponseUtil.fail(1000)));
        } catch (Exception e) {
            log.error("【DSFFormAuthenticationFilter】，异常", e);
        }
        return false;
    }

}
